<template>
  <div class="cr-body-content">
    <flexbox :class="isRelationShow && 'content-header-no-space'" class="content-header">
      <div v-if="!isRelationShow">场景：</div>
      <el-dropdown
        v-if="!isRelationShow"
        trigger="click"
        @command="handleTypeDrop">
        <flexbox>
          <div>{{ sceneInfo ? sceneInfo.name : '请选择' }}</div>
          <i
            class="el-icon-arrow-down el-icon--right"
            style="color:#777;"/>
        </flexbox>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item
            v-for="(item, index) in scenesList"
            :key="index"
            :command="item ">{{ item.name }}</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
      <el-input
        v-model="searchContent"
        class="search-container" @change.native="searchInput">
        <el-button
          slot="append"
          icon="el-icon-search"
          @click.native="searchInput"/>
      </el-input>
      <el-button
        v-if="showCreateButton()"
        type="primary"
        @click.native="createClick">{{ showCreateTitle }}</el-button>
    </flexbox>
    <el-table
      v-loading="loading"
      ref="relativeTable"
      :data="list"
      :height="250"
      class="cr-table"
      stripe
      border
      highlight-current-row
      style="width: 100%"
      @select-all="selectAll"
      @selection-change="handleSelectionChange"
      @row-click="handleRowClick">
      <el-table-column
        show-overflow-tooltip
        type="selection"
        align="center"
        width="55"/>
      <el-table-column
        v-for="(item, index) in fieldList"
        :key="index"
        :prop="item.field"
        :label="item.name"
        :width="150"
        show-overflow-tooltip/>
      <el-table-column/>
    </el-table>
    <div class="table-footer" >
      <el-button
        :disabled="currentPage <= 1"
        @click.native="changePage('up')">上一页</el-button>
      <el-button
        :disabled="currentPage >= totalPage"
        @click.native="changePage('down')">下一页</el-button>
      <span>当前页：{{ currentPage + ' / ' +  totalPage}}，显示{{list.length}}条，已选中{{selectedItem.length}}</span>
    </div>
    <c-r-m-create-view
      v-if="isCreate"
      :action="createActionInfo"
      :crm-type="crmType"
      @save-success="getList"
      @hiden-view="isCreate=false"/>
  </div>
</template>
<script type="text/javascript">
import {
  mapGetters
} from 'vuex'
import crmTypeModel from '@/views/customermanagement/model/crmTypeModel'
import psiTypeModel from '@/views/psimanagement/model/psiTypeModel'
import financeTypeModel from '@/views/financemanagement/model/financeTypeModel'
import { crmLeadsIndex } from '@/api/customermanagement/leads'
import { crmCustomerIndex } from '@/api/customermanagement/customer'
import { crmContactsIndex } from '@/api/customermanagement/contacts'
import { crmBusinessIndex } from '@/api/customermanagement/business'
import { crmContractIndex } from '@/api/customermanagement/contract'
import { crmQuotationQueryProductList,queryQuotationsByBusiness } from '@/api/customermanagement/quotation'
import { crmSceneIndex } from '@/api/customermanagement/common'
// psi部分
import { psiStorehouseIndex } from '@/api/psimanagement/storehouse'
import { financeSupplierIndex } from '@/api/financemanagement/supplier'
import { getFileList, getFileById } from '@/api/kmsmanagement/file'
import { getSourceList, getSourceById } from '@/api/kmsmanagement/source'
// 客户下商机和联系人
import {
  crmCustomerQueryBusiness,
  crmCustomerQueryContract,
  crmCustomerQueryContacts
} from '@/api/customermanagement/customer'
import { crmBusinessQueryContactsAPI } from '@/api/customermanagement/business'
export default {
  name: 'CrmRelativeTable', // 相关模块CRMCell
  components: {
    CRMCreateView: () =>
      import('@/views/customermanagement/components/CRMCreateView')
  },
  props: {
    show: {
      type: Boolean,
      default: false
    },
    /** 多选框 只能选一个 */
    radio: {
      type: Boolean,
      default: true
    },
    /** 没有值就是全部类型 有值就是当个类型 */
    crmType: {
      type: String,
      default: ''
    },
    /** 已选信息 */
    selectedData: {
      type: Object,
      default: () => {
        return {}
      }
    },
    /**
     * default 默认  condition 固定条件筛选
     * relative: 相关 添加
     */
    action: {
      type: Object,
      default: () => {
        return {
          type: 'default',
          data: {}
        }
      }
    },
    isValidAll: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      loading: false, // 加载进度
      searchContent: '', // 输入内容
      isCreate: false, // 控制新建
      scenesList: [], // 场景信息
      sceneInfo: null,

      list: [], // 表数据
      fieldList: [], // 表头数据
      currentPage: 1, // 当前页数
      totalPage: 1, // 总页数
      createActionInfo: {}, // 新建页面时，传入的参数
      otherItems: [],
      showCreateTitle: '', // 新建按钮名称
      selectedItem: [] // 勾选的数据 点击确定 传递给父组件
    }
  },
  computed: {
    ...mapGetters(['crm']),
    // 展示相关效果 去除场景
    isRelationShow() {
      return this.action.type === 'condition'
    },
    // 是否存在公海查看权限
    isHaveSeas() {
      return this.crm.pool && this.crm.pool.index ? this.crm.pool.index : false
    }
  },
  watch: {
    crmType: function(newValue, oldValue) {
      if (newValue != oldValue) {
        this.fieldList = []
        this.getFieldList()
      }
    },
    action: function(val) {
      this.sceneInfo = null
      this.list = [] // 表数据
      this.fieldList = [] // 表头数据
      this.currentPage = 1 // 当前页数
      this.totalPage = 1 // 总页数
      if(this.show){
        if (!this.isRelationShow) {
          this.getSceneList()
        } else {
          this.getFieldList()
        }
      }
    },
    show: {
      handler(val) {
        if (val && this.fieldList.length == 0) {
          // 相关列表展示时不需要场景 直接获取展示字段
          if (!this.isRelationShow) {
            this.getSceneList()
          } else {
            this.getFieldList()
          }
        }
      },
      deep: true,
      immediate: true
    },
    // 选择
    selectedData: function() {
      this.checkItemsWithSelectedData()
    }
  },
  mounted() {},
  methods: {
    /**
     * 刷新列表
     */
    refreshList() {
      this.currentPage = 1
      this.getList()
    },

    getSceneList() {
      this.loading = true
      var indexParm = ''
      if (this.crmType == 'storehouse' || this.crmType == 'customer_all') {
        indexParm = psiTypeModel[this.crmType]
      } else if (this.crmType == 'supplier') {
        indexParm = financeTypeModel[this.crmType]
      } else if (this.crmType == 'kmsSource') {
        indexParm = 100
      } else if (this.crmType == 'kmsCourse') {
        indexParm = 101
      } else {
        indexParm = crmTypeModel[this.crmType]
      }
      crmSceneIndex({
        type: indexParm
      })
        .then(res => {
          var defaultScene = res.data.filter(function(item, index) {
            return item.isDefault === 1
          })
          this.scenesList = res.data
          if (defaultScene && defaultScene.length > 0) {
            this.sceneInfo = defaultScene[0]
          }
          if (this.scenesList.length == 0) {
            this.scenesList.push({ sceneId: '', name: '全部' })
            this.sceneInfo = this.scenesList[0]
          }
          this.getFieldList()
        })
        .catch(() => {
          this.loading = false
        })
    },
    /** 获取字段 */
    getFieldList() {
      if (this.fieldList.length == 0) {
        this.fieldList = this.getDefaultField()
      }
      // 获取好字段开始请求数据
      this.getList()
    },
    /** 获取列表请求 */
    getDefaultField() {
      if (this.crmType === 'leads' || this.crmType === 'customer' || this.crmType === 'customer_all') {
        return [
          { name: '客户名称', field: 'customerName', formType: 'customer' },
          { name: '下次联系时间', field: 'nextTime', formType: 'datetime' },
          { name: '最后跟进时间', field: 'updateTime', formType: 'datetime' },
          { name: '客户类型', field: 'customerTypeValue', formType: 'text' },
          { name: '创建时间 ', field: 'createTime', formType: 'datetime' }
        ]
      } else if (this.crmType === 'contacts') {
        return [
          { name: '姓名', field: 'name', formType: 'contacts' },
          { name: '手机', field: 'mobile', formType: 'mobile' },
          { name: '电话', field: 'telephone', formType: 'text' },
          { name: '是否关键决策人', field: '是否关键决策人', formType: 'text' },
          { name: '职务', field: 'post', formType: 'text' }
        ]
      } else if (this.crmType === 'business') {
        return [
          { name: '商机名称', field: 'businessName', formType: 'text' },
          { name: '商机金额', field: 'money', formType: 'text' },
          { name: '客户名称', field: 'customerName', formType: 'text' },
          // { name: '商机状态组 ', field: 'typeName', formType: 'text' },
          { name: '状态 ', field: 'statusName', formType: 'text' }
        ]
      } else if (this.crmType === 'quotation') {
        return [
          { name: '报价单号', field: 'quotationNumber', formType: 'text' },
          { name: '部署方式', field: 'quotationItemId', formType: 'text' },
          { name: '总价', field: 'finalSalesPriceTax', formType: 'text' },
          { name: '报价日期 ', field: 'quotationDate', formType: 'text' },
          { name: '有效期 ', field: 'validPeriod', formType: 'text' },
          { name: '备注 ', field: 'remark', formType: 'text' },
        ]
      } else if (this.crmType === 'contract') {
        return [
          { name: '合同编号', field: 'num', formType: 'text' },
          {
            name: '合同名称',
            field: this.isRelationShow ? 'contractName' : 'name',
            formType: 'text'
          },
          { name: '客户名称', field: 'customerName', formType: 'text' },
          { name: '合同金额', field: 'money', formType: 'text' },
          { name: '开始日期', field: 'startTime', formType: 'text' },
          { name: '结束日期', field: 'endTime', formType: 'text' }
        ]
      } else if (this.crmType === 'product') {
        return [
          { name: '产品名称', field: 'name', formType: 'text' },
          { name: '产品编号', field: 'num', formType: 'text' },
          { name: '规格', field: 'specName', formType: 'text' },
          { name: '产品简介', field: 'description', formType: 'text' },
          { name: '库存数量', field: 'balance', formType: 'text' },
          { name: '单位', field: 'unit', formType: 'text' },
        ]
      } else if (this.crmType === 'storehouse') {
        return [
          { name: '仓库', field: 'name', formType: 'text' },
          { name: '仓库编号', field: '仓库编号', formType: 'text' }
        ]
      } else if (this.crmType === 'supplier') {
        return [
          { name: '供应商名称', field: 'name', formType: 'text' },
          { name: '供应商简称', field: '供应商简称', formType: 'text' },
          { name: '备注', field: '备注', formType: 'text' }
        ]
      } else if (this.crmType === 'kmsSource') {
        return [
          { name: '文件名称', field: 'title', formType: 'text' },
          { name: '文件简介', field: 'content', formType: 'textarea' },
          { name: '负责人', field: 'ownerUserName', formType: 'text' }
        ]
      } else if (this.crmType === 'kmsCourse') {
        return [
          { name: '资源名称', field: 'title', formType: 'text' },
          { name: '资源内容', field: 'remarks', formType: 'textarea' },
          { name: '资源分类', field: 'categoryName', formType: 'select' }
        ]
      }
    },
    /** 获取列表数据 */
    getList() {
      this.loading = true
      let crmIndexRequest = this.getIndexRequest()
      let params = { search: this.searchContent }
      // 注入场景
      if (this.sceneInfo) {
        params.sceneId = this.sceneInfo.sceneId
      }
      // 注入关联ID
      if (this.isRelationShow) {
        // this.action.data.moduleType 下的 this.crmType 的列表
        if (this.action.data.moduleType) {
          crmIndexRequest = {
            leads: {
              business: crmCustomerQueryBusiness,
              contacts: crmCustomerQueryContacts,
              contract: crmCustomerQueryContract
            },
            customer: {
              business: crmCustomerQueryBusiness,
              contacts: crmCustomerQueryContacts,
              contract: crmCustomerQueryContract
            },
            business: {
              business: crmCustomerQueryBusiness,
              quotation: queryQuotationsByBusiness,
              contacts: crmBusinessQueryContactsAPI
            }
          }[this.action.data.moduleType][this.crmType]
          if (this.action.data.moduleType == 'leads') {
            params['customerId'] = this.action.data['customerId']
          } else {
            params[this.action.data.moduleType + 'Id'] = this.action.data[
              this.action.data.moduleType + 'Id'
            ]
          }
          if (this.action.data.params) {
            for (const field in this.action.data.params) {
              params[field] = this.action.data.params[field]
            }
          }
        }
      } else {
        params.page = this.currentPage
        params.limit = 10
        if (this.crmType == 'storehouse') {
          params.type = psiTypeModel[this.crmType]
        } else if (this.crmType == 'supplier') {
          params.type = financeTypeModel[this.crmType]
        } else if (this.crmType == 'customer_all') {
          params.type = psiTypeModel[this.crmType]
          params.isTotalCustomer = true
        } else {
          params.type = crmTypeModel[this.crmType]
        }
        // params.type = crmTypeModel[this.crmType]
      }

      if (this.crmType == 'customer') {
        // 不同功能模块下，触发客户查询
        if (this.action.data.pageType != 'contacts') {
          params.isValid = true
        } else {
          // 查询全部客户（潜在+目标+公海）
          params.isTotalCustomer = true
          params.isHaveSeas = this.isHaveSeas
        }
      } else if(this.crmType == 'product'){
        params.page = this.currentPage
        params.limit = 10
        params.itemOption = this.action.data.item.itemOption;
        params.quotationItemId = this.action.data.item.quotationItemId;
      }
      // 关联商机，必须是审核通过
      if (this.crmType == 'business') {
        if(this.action.data.pageType == 'preSales'){
          params.status_id = 1;
        }
        if(this.action.data.pageType == 'quotation'){
          params.status_id = 3;
        }
        if(this.action.data.pageType == 'contract'){
          params.status_id = 6;
        }
        if (this.isValidAll) {
          params.isValid = false
        } else {
          params.isValid = true
        }
      }

      // 关联报价，必须是审核通过
      if (this.crmType == 'quotation') {
        params.isValid = true
      }
      // eslint-disable-next-line no-cond-assign
      if (this.searchContent != '' && (this.crmType == 'kmsSource' || this.crmType == 'kmsCourse')) {
        // eslint-disable-next-line no-const-assign
        params['search'] = this.searchContent
      }
      crmIndexRequest(params)
        .then(res => {
          this.list = res.data.list
          /**
           *  如果已选择的有数据
           */
          if (this.selectedData[this.crmType]) {
            this.checkItemsWithSelectedData()
          } else {
            this.list = res.data.list
          }
          this.handleData()
          this.totalPage = res.data.totalRow ? Math.ceil(res.data.totalRow / 10) : 1
          this.loading = false
        })
        .catch(() => {
          this.loading = false
        })
    },
    // 标记选择数据
    checkItemsWithSelectedData() {
      const selectedArray = this.selectedData[this.crmType].map(item => {
        item.has = false
        return item
      })

      const selectedRows = []
      this.otherItems = []

      let crmType = '';
      if(this.crmType == 'kmsSource'){
        crmType = 'file'
      }else if (this.crmType == 'kmsCourse'){
        crmType = 'resource'
      }else{
        crmType = this.crmType;
      }

      this.list.forEach((item, index) => {
        selectedArray.forEach((selectedItem, selectedIndex) => {
          if (item[crmType + 'Id'] == selectedItem[crmType + 'Id']) {
            selectedItem.has = true
            selectedRows.push(item)
          }
        })
      })

      selectedArray.forEach((selectedItem, selectedIndex) => {
        if (!selectedItem.has) {
          this.otherItems.push(selectedItem)
        }
      })

      this.$nextTick(() => {
        this.$refs.relativeTable.clearSelection()
        selectedRows.forEach(row => {
          this.$refs.relativeTable.toggleRowSelection(row, true)
        })
      })
    },

    // 对返回的数据进行处理
    handleData() {
      const list = this.list
      if (this.crmType == 'customer') {
        for (let i = 0; i < list.length; i++) {
          list[i].customerTypeValue = list[i].customerType == 1 ? '潜在客户' : '目标客户'
        }
      }
    },
    /** 获取列表请求 */
    getIndexRequest() {
      if (this.crmType === 'leads') {
        return crmLeadsIndex
      } else if (this.crmType === 'customer') {
        return crmCustomerIndex
      } else if (this.crmType === 'contacts' || this.crmType === 'follow_contacts') {
        return crmContactsIndex
      } else if (this.crmType === 'business') {
        return crmBusinessIndex
      } else if (this.crmType === 'contract') {
        return crmContractIndex
      } else if (this.crmType === 'product') {
        return crmQuotationQueryProductList
      } else if (this.crmType === 'storehouse') {
        return psiStorehouseIndex
      } else if (this.crmType === 'supplier') {
        return financeSupplierIndex
      } else if (this.crmType === 'customer_all') {
        return crmCustomerIndex
      } else if (this.crmType == 'kmsSource') {
        return getFileList
      } else if (this.crmType == 'kmsCourse') {
        return getSourceList
      } else if (this.crmType == 'quotation') {
        return queryQuotationsByBusiness
      }
    },
    // 场景选择
    handleTypeDrop(command) {
      this.sceneInfo = command
      this.getList()
    },
    /** 列表操作 */
    // 当某一行被点击时会触发该事件
    handleRowClick(row, column, event) {
      this.$refs.relativeTable.toggleRowSelection(row)
    },
    // 当选择项发生变化时会触发该事件
    handleSelectionChange(val) {
      if (this.radio) {
        // this.$refs.relativeTable.clearSelection();
        val.forEach((row, index) => {
          if (index === val.length - 1) return
          this.$refs.relativeTable.toggleRowSelection(row, false)
        })
        if (val.length === 0) {
          this.selectedItem = []
        } else {
          this.selectedItem = val.length === 1 ? val : [val[val.length - 1]]
        }
      } else {
        this.selectedItem = this.otherItems.concat(val)
      }
      this.$emit('changeCheckout', {
        data: this.selectedItem,
        type: this.crmType
      })
    },
    clearAll() {
      this.$refs.relativeTable.clearSelection()
    },
    // 	当用户手动勾选全选 Checkbox 时触发的事件
    selectAll() {},
    // 进行搜索操作
    searchInput() {
      this.currentPage = 1
      this.totalPage = 1
      this.getList()
    },
    changePage(type) {
      if (type == 'up') {
        this.currentPage = this.currentPage - 1
      } else if (type == 'down') {
        this.currentPage = this.currentPage + 1
      }
      if (this.currentPage <= this.totalPage && this.currentPage >= 1) {
        this.getList()
      }
    },

    /** 新建 */
    createClick() {
      /** 客户 下新建联系人 */
      this.createActionInfo['data'] = {}
      this.createActionInfo['crmType' ] = this.action.data.moduleType
      if (this.action.data && this.action.data.moduleType == 'customer') {
        this.createActionInfo['type' ] = 'relative'
        this.createActionInfo.data[this.action.data.moduleType] = this.action.data.detail
      }
      this.isCreate = true
    },

    showCreateButton() {
      if (this.crmType === 'contacts') {
        this.showCreateTitle = '新建联系人'
        return true
      }
      return false
    }
  }
}
</script>
<style lang="scss" scoped>
.cr-body-content {
  position: relative;
  background-color: white;
  border-bottom: 1px solid $xr-border-line-color;
}

.content-header {
  position: relative;
  padding: 10px 20px;
  .search-container {
    margin: 0 20px;
    width: 200px;
  }
  .create-button {
    position: absolute;
    right: 10px;
    top: 15px;
  }
  &.content-header-no-space {
    padding: 10px 0px;
    .search-container {
      margin-left: 0;
    }
  }
}

//表尾 上一页按钮
.table-footer {
  padding: 8px 20px;
}

.el-table /deep/ thead th {
  font-weight: 400;
  font-size: 12px;
}

.el-table /deep/ tbody tr td {
  font-size: 12px;
}

.el-table /deep/ thead .el-checkbox {
  display: none;
}

body .el-table th.gutter {
  display: table-cell !important;
}

.el-table /deep/ .el-table__body-wrapper {
  height: calc(100% - 48px) !important;
}
</style>
